//
//  Refresh.swift
//  ADKit
//
//  Created by Adoma on 2024/01/15.
//

import RxSwift
import RxCocoa

public protocol ADRefreshComponentType: NSObjectProtocol {
    func set(target: AnyObject, action: Selector)
}

public extension Reactive where Base: ADRefreshComponentType {
    
    /// by ADKit
     var beginRefreshing: Observable<Void> {
        
        Observable.create {[weak control = self.base] observer in
            MainScheduler.ensureRunningOnMainThread()
            
            guard let control = control else {
                observer.on(.completed)
                return Disposables.create()
            }
            
            let controlTarget = RefeshingTarget(control: control) {
                observer.on(.next(Void()))
            }
            
            return Disposables.create(with: controlTarget.dispose)
        }
    }
}

private class RefeshingTarget: NSObject, Disposable {
    
    let selector: Selector = #selector(RefeshingTarget.eventHandler)
    
    typealias Callback = () -> Void
    var callback: Callback?
    
    private var retainSelf: RefeshingTarget?
    
    init(control: ADRefreshComponentType, callback: @escaping Callback) {
        
        self.callback = callback
        
        super.init()
        self.retainSelf = self
        
        control.set(target: self, action: selector)
    }
    
    @objc func eventHandler() {
        callback?()
    }
    
    func dispose() {
        self.retainSelf = nil
        self.callback = nil
    }
    
    deinit {
        ADLogger(adkit: Self.self)
            .debug(#function)
    }
}

